package cn.aishua.ui.myKaka;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import cn.aishua.data.BankCardInfo;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.util.FormatConverter;
import cn.aishua.util.Utils;

import cn.aishua.R;

public class MyBankCardActivity
    extends ListActivity
{
    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    private List<BankCardInfo> bankCardList;

    private LinearLayout lLAddCardItem;

    public final static String EXTRA_DATA_BOOL_IS_EXCHANGE_CARD = "EXTRA_DATA_BOOL_IS_VISIBLE";
    public final static String EXTRA_DATA_STR_BANK_TYPE = "EXTRA_DATA_STR_BANK_TYPE";
    public final static String EXTRA_DATA_STR_CARD_NUM = "EXTRA_DATA_STR_CARD_NUM";
    public final static String EXTRA_DATA_STR_CARD_TYPE = "EXTRA_DATA_STR_CARD_TYPE";
    public final static String EXTRA_DATA_STR_DATE = "EXTRA_DATA_STR_DATE";
    public final static String EXTRA_DATA_STR_CREDIT = "EXTRA_DATA_STR_CREDIT";
    public final static String EXTRA_DATA_INT_CARD_ID = "EXTRA_DATA_INT_CARD_ID";
    public final static String EXTRA_DATA_PAR_CARD_INFO = "EXTRA_DATA_PAR_CARD_INFO";

    @Override
    public void onCreate( Bundle savedInstanceState )
    {
        Log.d( "MyBankCardActivity", "onCreate()" );
        super.onCreate( savedInstanceState );
        setContentView( R.layout.my_kaka_my_bank_card );
        initPageHeader();
        initiate();

    }

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_back );
        ivLeftBtn.setOnClickListener( new OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                onBackPressed();
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "我的银行卡" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setImageResource( R.drawable.btn_add );
        ivRightBtn.setOnClickListener( new OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                addCard( v );
            }
        } );
    }

    private void initiate()
    {

        lLAddCardItem = (LinearLayout) findViewById( R.id.my_kaka_my_bank_card_ll_add );

        ListView listView = getListView();
        MyAdapter adapter = new MyAdapter( this );
        listView.setAdapter( adapter );
        listView.setDividerHeight( 0 );
    }

    @Override
    protected void onResume()
    {
        Log.d( getClass().getSimpleName(), "onResume()" );
        super.onResume();

        new DataExchangeAsyncTask( this, "获取银行卡" )
        {

            @Override
            protected void handleSuccResponse( String strJson ) throws Exception
            {
                Log.d( "json response", strJson );
                JSONObject jsonObject = new JSONObject( strJson );
                JSONArray jsonArray = jsonObject.getJSONArray( "bank_card" );
                if( jsonArray != null && jsonArray.length() > 0 )
                {
                    bankCardList = new ArrayList<BankCardInfo>();
                    int length = jsonArray.length();
                    for( int i = 0; i < length; i++ )
                    {
                        JSONObject item = jsonArray.getJSONObject( i );
                        String bankType = item.getString( "bank_display_name" );
                        String cardNum = item.getString( "card_number" );
                        int cardType = item.getInt( "card_type" );// 0 - deposit card; 1 - credit card
                        String date = item.getString( "created_at" );
                        int credit = item.getInt( "credit_earned" );
                        boolean isCashingCard = item.getBoolean( "cashing_card" );
                        int cardId = item.getInt( "id" );
                        bankCardList.add( new BankCardInfo( cardId, bankType,
                            FormatConverter.toCardNumFormat( cardNum ), cardType == 0 ? "储蓄卡" : "信用卡", date, credit,
                            isCashingCard ? 1 : 0 ) );
                    }
                    ( (MyAdapter) MyBankCardActivity.this.getListView().getAdapter() ).notifyDataSetChanged();

                }

                if( bankCardList != null && bankCardList.size() > 4 )
                {
                    lLAddCardItem.setVisibility( View.GONE );
                }
                else
                {
                    lLAddCardItem.setVisibility( View.VISIBLE );
                }

            }

            @Override
            protected HttpResponse sendRequest( String... params )
            {
                //                return HttpRequestUtil.getInstance().request( "", HttpRequestUtil.HTTP_METHOD_GET );
                return HttpRequestUtil.getInstance().getBankCards();
            }

        }.execute();
    }

    public void addCard( View view )
    {
        if( bankCardList != null && bankCardList.size() == 5 )
        {
            Toast.makeText( this, "最多允许添加5张银行卡，请删除不常用的卡再进行添加", Toast.LENGTH_SHORT ).show();
        }
        else
        {
            Intent addCardIntent = new Intent( this, AddBankCardActivity.class );
            startActivity( addCardIntent );
        }
    }

    public void toDetailPage( View view )
    {

        ViewHolder holder = (ViewHolder) view.getTag();

        String bankType = holder.tvBankType.getText().toString();
        String cardType = holder.tvCardType.getText().toString();
        String cardNum = holder.tvCardNum.getText().toString();
        String date = holder.strDate;
        String credit = holder.strCredit;
        int cardId = holder.intCardId;

        Intent toDetailPage = new Intent( this, MyBankCardDetailActivity.class );
        toDetailPage
            .putExtra( EXTRA_DATA_BOOL_IS_EXCHANGE_CARD, holder.ivSetAsExchange.getVisibility() == View.VISIBLE );
        toDetailPage.putExtra( EXTRA_DATA_STR_BANK_TYPE, bankType );
        toDetailPage.putExtra( EXTRA_DATA_STR_CARD_TYPE, cardType );
        toDetailPage.putExtra( EXTRA_DATA_STR_CARD_NUM, cardNum );
        toDetailPage.putExtra( EXTRA_DATA_STR_DATE, date );
        toDetailPage.putExtra( EXTRA_DATA_STR_CREDIT, credit );
        toDetailPage.putExtra( EXTRA_DATA_INT_CARD_ID, cardId );

        startActivity( toDetailPage );
    }

    public final class ViewHolder
    {
        public ImageView ivBankIcon;
        public TextView tvBankType;
        public TextView tvCardType;
        public TextView tvCardNum;
        public ImageView ivSetAsExchange;
        // these values are needed for detail page
        public String strDate;
        public String strCredit;
        public int intCardId;
    }

    public class MyAdapter
        extends BaseAdapter
    {

        private LayoutInflater mInflater;

        public MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from( context );
        }

        public int getCount()
        {
            Log.d( "bankcardList", "getCount()" );
            if( bankCardList != null )
            {
                return bankCardList.size();
            }
            else
            {
                return 0;
            }
        }

        public Object getItem( int position )
        {
            Log.d( "bankcardList", "getItem()" );
            return bankCardList.get( position );
        }

        public long getItemId( int position )
        {
            return position;
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            Log.d( "bankcardList", "getView()" );
            ViewHolder holder = null;
            if( convertView == null )
            { // when the first bank card is added into this view 
                holder = new ViewHolder();
                convertView = mInflater.inflate( R.layout.bank_card_item, null );
                holder.ivBankIcon = (ImageView) convertView.findViewById( R.id.my_kaka_my_bank_card_iv_bank_icon );
                holder.tvBankType = (TextView) convertView.findViewById( R.id.my_kaka_my_bank_card_tv_bank_type );
                holder.tvCardType = (TextView) convertView.findViewById( R.id.my_kaka_my_bank_card_tv_card_type );
                holder.tvCardNum = (TextView) convertView.findViewById( R.id.my_kaka_my_bank_card_tv_card_num );
                holder.ivSetAsExchange = (ImageView) convertView
                    .findViewById( R.id.my_kaka_my_bank_card_tv_set_as_exchange );
                convertView.setTag( holder );
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            BankCardInfo item = bankCardList.get( position );

            String bankType = item.getBankType();
            String cardType = item.getCardType();
            String cardNum = item.getCardNum();
            boolean isSetAsExchange = item.getExchangeCard() == 1;

            holder.tvBankType.setText( bankType );
            holder.tvCardType.setText( cardType );
            holder.tvCardNum.setText( cardNum );

            Log.d( "MyAdapter", "cardNum: " + cardNum );

            if( isSetAsExchange )
            {
                holder.ivSetAsExchange.setVisibility( View.VISIBLE );
            }
            else
            {
                holder.ivSetAsExchange.setVisibility( View.INVISIBLE );
            }

            holder.strDate = item.getDate();
            holder.strCredit = String.valueOf( item.getCredit() );
            holder.intCardId = item.getCardId();

            holder.ivBankIcon.setImageResource( Utils.getIconResId( getApplicationContext(), bankType ) );

            return convertView;
        }

    }

}
